import type { App, Directive } from 'vue'
import { usePermission } from '@/hooks/usePermission'

// 权限检查函数
function checkPermission(el: HTMLElement, binding: any) {
  const { value } = binding
  const { hasPermission } = usePermission()

  if (value && typeof value === 'string') {
    const hasPermissionResult = hasPermission(value)

    // 如果没有权限，则隐藏元素
    if (!hasPermissionResult) {
      el.style.display = 'none'
    } else {
      el.style.display = ''
    }
  } else {
    throw new Error('v-auth 指令值必须是字符串类型')
  }
}

const authDirective: Directive = {
  mounted(el, binding) {
    checkPermission(el, binding)
  },
  updated(el, binding) {
    checkPermission(el, binding)
  },
}

export function setupAuthDirective(app: App) {
  app.directive('auth', authDirective)
}

export default authDirective
